//
//  GZNPasswdViewController.m
//  Cattle
//
//  Created by zhangmeng on 14-5-28.
//  Copyright (c) 2014年 xxcao. All rights reserved.
//

#import "BCPasswordViewController.h"
#import "BarCode-Swift.h"
#import "SVProgressHUD.h"
#import <BmobSDK/bmob.h>
#import "CommonFunc.h"

@interface BCPasswordViewController ()

@property(assign,nonatomic) NSInteger finish;

@end

@implementation BCPasswordViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"修改密码";

    self.finish = 0;
    [self customBackBarItem];
    [self customRightBarItem:@"完成"];
    
    self.bgImgV.layer.borderWidth = 1.0 / [UIScreen mainScreen].scale;
    self.bgImgV.layer.borderColor = [UIColor colorWithRed:229.0 / 255 green:229.0 / 255 blue:229.0 / 255 alpha:1.0].CGColor;
    
    CGRect line1Frame = self.line1ImgV.frame;
    line1Frame.size.height = 1.0 / [UIScreen mainScreen].scale;
    self.line1ImgV.frame = line1Frame;
    
    CGRect line2Frame = self.line2ImgV.frame;
    line2Frame.size.height = 1.0 / [UIScreen mainScreen].scale;
    self.line2ImgV.frame = line2Frame;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if(![self.oldPss isFirstResponder]){
        [self.oldPss becomeFirstResponder];
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.oldPss resignFirstResponder];
    [self.nwePss resignFirstResponder];
    [self.surePss resignFirstResponder];
}


- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.oldPss resignFirstResponder];
    [self.nwePss resignFirstResponder];
    [self.surePss resignFirstResponder];
    return YES;
}

-(void)doneClick {
    
    [self.oldPss resignFirstResponder];
    [self.nwePss resignFirstResponder];
    [self.surePss resignFirstResponder];
    if([BCPasswordViewController isEmptyString:self.oldPss.text]){
        [SVProgressHUD showErrorWithStatus:@"请输入原密码"];
        [SVProgressHUD dismissWithDelay:2.0];
        return;
    }
    else if([BCPasswordViewController isEmptyString:self.surePss.text] && [BCPasswordViewController isEmptyString:self.nwePss.text])
    {
        [SVProgressHUD showErrorWithStatus:@"请输入新密码"];
        [SVProgressHUD dismissWithDelay:2.0];
        return;
    }
    else if([BCPasswordViewController isEmptyString:self.surePss.text]){
        [SVProgressHUD showErrorWithStatus:@"请再次确认密码"];
        [SVProgressHUD dismissWithDelay:2.0];
        return;
    }
    else if([BCPasswordViewController isEmptyString:self.nwePss.text]){
        [SVProgressHUD showErrorWithStatus:@"请输入新密码"];
        [SVProgressHUD dismissWithDelay:2.0];
        return;
    }
    else if(![self.nwePss.text isEqualToString:self.surePss.text]){
        [SVProgressHUD showErrorWithStatus:@"新密码与确认密码不一致"];
        [SVProgressHUD dismissWithDelay:2.0];
        return;
    }
    else if (self.nwePss.text.length < 6){
        [SVProgressHUD showErrorWithStatus:@"密码不能少于6位"];
        [SVProgressHUD dismissWithDelay:2.0];
        return;
    }
    else if (self.nwePss.text.length >12){
        [SVProgressHUD showErrorWithStatus:@"密码不能多于12位"];
        [SVProgressHUD dismissWithDelay:2.0];
        return;
    }
    else if([BCPasswordViewController isCharacter:self.nwePss.text]){
        [SVProgressHUD showErrorWithStatus:@"密码请输入字母或数字"];
        [SVProgressHUD dismissWithDelay:2.0];
        return;
    }
    else if([BCPasswordViewController isIllegalPassword:self.nwePss.text]){
        [SVProgressHUD showErrorWithStatus:@"密码请输入字母、数字、下划线"];
        [SVProgressHUD dismissWithDelay:2.0];
        return;
    }
    else if(self.nwePss.text.length < 6){
        [SVProgressHUD showErrorWithStatus:@"密码输入过短"];
        [SVProgressHUD dismissWithDelay:2.0];
        return;
    }
    else if(self.nwePss.text.length > 12){
        [SVProgressHUD showErrorWithStatus:@"密码输入过长"];
        [SVProgressHUD dismissWithDelay:2.0];
        return;
    }
    
    //to do
    [SVProgressHUD show];
    [CommonFunc modifyPasswordWithOldPassword:self.oldPss.text newPassword:self.nwePss.text block:^(id results, int status) {
        if (status == 1) {
            [SVProgressHUD dismissWithDelay:1.5 completion:^{
                [SVProgressHUD showSuccessWithStatus:results];
                //删除密码
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"dream.BarCode.userDefaults.key.userPsd"];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    BCLoginViewController *rootVC = [[BCLoginViewController alloc] init];
                    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                    appDelegate.window.rootViewController = rootVC;
                    [appDelegate.window makeKeyAndVisible];
                });
            }];
        } else {
            [SVProgressHUD dismissWithDelay:1.5 completion:^{
                [SVProgressHUD showSuccessWithStatus:results];
            }];
        }
    }];
}
//MARK: -自定义方法
- (void)customBackBarItem {
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
    leftBarItem.image = [UIImage imageNamed:@"backBtnU"];
    
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    space.width = 8;
    self.navigationItem.leftBarButtonItems = @[space, leftBarItem];
}

- (void)customRightBarItem:(NSString *)str{
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(doneClick)];
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    space.width = 8;
    self.navigationItem.rightBarButtonItems = @[rightBarItem, space];
}

- (void)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

//MARK: - 字符串校验
+ (BOOL)isEmptyString:(NSString *)sourceStr {
    if ((NSNull *)sourceStr == [NSNull null]) {
        return YES;
    }
    if (sourceStr == nil) {
        return YES;
    }
    if (sourceStr == NULL) {
        return YES;
    }
    if ([sourceStr isEqual:[NSNull null]]) {
        return YES;
    }
    if (![sourceStr isKindOfClass:[NSString class]]) {
        return YES;
    }
    if([sourceStr isEqualToString:@"<null>"]){
        return YES;
    }
    if ([sourceStr isEqualToString:@"null"]) {
        return YES;
    }
    if ([sourceStr isEqualToString:@""]) {
        return YES;
    }
    if (sourceStr.length == 0) {
        return YES;
    }
    return NO;
}

+ (BOOL)isCharacter:(NSString *)characterNum {
    NSMutableCharacterSet *letterBase = [NSMutableCharacterSet letterCharacterSet];   //字母
    NSCharacterSet *decimalDigit = [NSCharacterSet decimalDigitCharacterSet];   //十进制数字
    [letterBase formUnionWithCharacterSet:decimalDigit];    //字母加十进制
    [letterBase invert];
    NSRange userNameRange = [characterNum rangeOfCharacterFromSet:letterBase];
    if (userNameRange.location != NSNotFound) {
        return YES;
    } else{
        return NO;
    }
}

//判断密码合法性（这里规定：只能输入字母、数字、下划线）
+ (BOOL)isIllegalPassword:(NSString *)psdStr {
    BOOL isIllegal = NO;
    NSInteger len = psdStr.length;
    for (NSInteger i = 0; i < len; i++) {
        unichar uChar = [psdStr characterAtIndex:i];
        if (!((uChar >= 'a' && uChar <='z') ||
              (uChar >= 'A' && uChar <='Z') ||
              (uChar >= '0' && uChar <='9') ||
              (uChar == '_'))) {
            isIllegal = YES;
            break;
        }
    }
    return isIllegal;
}

@end
